import {getCurrentTimeString} from "../utils/time.js"
import {selectUserByMobile, addUser, selectUserById, selectUserByName} from "../service/user.js";
import {NO_AUTH_ERROR_CODE, REQUEST_PARAMS_ERROR_CODE} from "../exception/errorCode.js";
import MyError from "../exception/index.js";
import redis from "redis";
import redisClient from "../redis.js";
import {v4 as uuidv4} from "uuid";
import {getToken, setToken} from "../utils/token.js"
import {hashInfo} from "../utils/hash.js";

//用户注册接口
export async function register(event, req, res){
    const authResult = await getToken(event.auth)
    if (authResult){
        const userInfo = {
            name: hashInfo(event.name),
            password: hashInfo(event.password),
            mobile: hashInfo(event.mobile),
            register_time: getCurrentTimeString(),
        }

        await addUser(userInfo)

        return "注册成功"
    }else {
        throw MyError(REQUEST_PARAMS_ERROR_CODE,"验证码错误")
    }
}

//用户登录接口
export async function login(event, req, res){
    const userInfo = await selectUserByName(hashInfo(event.name))
    if(userInfo.length !== 0){
        const key = uuidv4()
        await setToken(key,userInfo[0].id)
        return {
            user:userInfo[0],
            token: key
        }
    }else {
        throw new MyError(REQUEST_PARAMS_ERROR_CODE,"账号或密码错误")
    }
}

//通过token获取用户信息
export async function getUserInfoByToken(event, req, res){
    if (event.Authorization){
        const userInfo = await selectUserById(event.Authorization)
        return userInfo[0]
    }else {
        console.log("未找到用户相关信息")
        throw new MyError(NO_AUTH_ERROR_CODE,"未找到用户相关信息")
    }
}
